<template>
  <div class='tag-container'>
     <el-card>
      <template #header v-if="$route.query.id">

          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>学科管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{$route.query.name}}</el-breadcrumb-item>
            <el-breadcrumb-item>标签管理</el-breadcrumb-item>
          </el-breadcrumb>

      </template>

        <el-row type="flex" justify="space-between">
            <el-col :span="18" :sm="18">
             <el-form size="small" >
              <el-row :gutter="10">
                <el-col :span="7" :xs="24" :sm="24" :md="24" :lg="7">
                <el-form-item label-width="80px" label="标签名称" style="width:270px">
                    <el-input  v-model="searchForm.tagName"></el-input>
                </el-form-item>
              </el-col>
               <el-col :span="7" :xs="24" :sm="24" :md="24" :lg="7">
                <el-form-item label-width="80px" label="状态" >
                     <el-select v-model="searchForm.state" placeholder="请选择">
                        <el-option
                          v-for="item in statusList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24" :sm="24" :md="24" :lg="5">
                <el-form-item >
                    <el-row >
                      <el-button size="small" @click="clear">清除</el-button>
                      <el-button size="small" type="primary" @click="hSearch">搜索</el-button>
                    </el-row>
                </el-form-item>
              </el-col>
              </el-row>
            </el-form>
            </el-col>

            <el-col :span="6" :sm="6">
              <el-row type="flex" justify="end">
                  <el-button type="text"  v-if="$route.query.id" @click="$router.back()"><i class="el-icon-back" ></i>返回学科</el-button>
                  <el-button type="success" size="small" @click="hAdd"><i class="el-icon-edit" /> 新增标签</el-button>
              </el-row>
            </el-col>
          </el-row>
           <el-alert
            :title="alertText"
            type="info"
            class="alert"
            :closable="false"
            show-icon
            ></el-alert>
         <el-table
           :header-cell-style="{background:'#fafafa'}"
          :data="tagList"
          style="width: 100%"
          >
          <el-table-column
          type="index"
          label="序号"
          width="80">
        </el-table-column>
         <el-table-column
          prop="subjectName"
          label="所属学科"
          width="210">
        </el-table-column>
         <el-table-column
          prop="tagName"
          label="标签名称"
          width="210">
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者"
          width="210">
        </el-table-column>
         <el-table-column
          label="创建日期"
          width="210">
          <template #default="{row}">
            {{formatDate(row.addDate)}}
          </template>
        </el-table-column>
         <el-table-column
          prop="twoLevelTag"
          label="状态"
          width="210">
          <template #default="{row}">
            {{row.state?'已启用':'已禁用'}}
          </template>
        </el-table-column>
         <el-table-column
          label="操作"
         >
          <template #default="{row}">
            <el-button type="text" @click="changState(row)" >{{row.state?'禁用':'启用'}}</el-button>
            <el-button type="text" @click="hEdit(row)" :disabled="row.state===1">修改</el-button>
            <el-button type="text" @click="hDel(row.id)" :disabled="row.state===1">删除</el-button>
          </template>
        </el-table-column>
          </el-table>
        <el-row type="flex" justify="end" class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            background
            @current-change="handleCurrentChange"
            :current-page="q.page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="q.pagesize"
            layout="prev,pager,next,sizes,jumper"
            :total="total">
          </el-pagination>
      </el-row>
       <el-dialog
        @closed="hClose"
        :visible.sync="showDialog"
        width="400px"
        :title="isEdit?'修改标签':'新增标签'"
        :close-on-click-modal="false"
     >
      <el-form label-width="80px" size="small" :model="tagForm" :rules="rules" ref="tagForm">
        <el-form-item label="所属学科" prop="subjectID" style="width:100%">
           <el-select v-model="tagForm.subjectID" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName" >
          <el-input placeholder="请输入标签名称" v-model="tagForm.tagName" ></el-input>
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
      <div class="close">
      <el-button @click="showDialog=false">取消</el-button>
      <el-button type="primary" @click="hSubmit">确认</el-button>
      </div>
    </div>
     </el-dialog>
     </el-card>
  </div>
</template>

<script>
import moment from 'moment'
import * as subjects from '@/api/hmmm/subjects.js'
import * as tags from '@/api/hmmm/tags.js'
import { status } from '@/api/hmmm/constants.js'
export default {
  data () {
    return {
      statusList: [],
      alertText: '共9条数据',
      tagList: [],
      subjectList: [],
      showDialog: false,
      isEdit: false,
      total: 10,
      tagForm: {
        subjectID: '',
        tagName: ''
      },
      searchForm: {
        tagName: '',
        state: ''
      },
      q: {
        page: 1,
        pagesize: 10
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        tagName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      }
    }
  },

  created () {
    this.statusList = status
    this.loadTagList()
    this.loadSubjectList()
  },
  methods: {
    hAdd () {
      this.isEdit = false
      this.showDialog = true
    },
    async doAdd () {
      try {
        const res = await tags.add(this.tagForm)
        console.log(res)
        if (res.status === 200) {
          this.loadTagList()
          this.showDialog = false
          this.$message.success('添加成功')
        }
      } catch (error) {
        console.log(error)
      }
    },
    hEdit (row) {
      this.isEdit = true
      this.showDialog = true
      this.tagForm = { ...row }
    },
    async doEdit () {
      try {
        const res = await tags.update(this.tagForm)
        console.log(res)
        if (res.status === 200) {
          this.loadTagList()
          this.showDialog = false
          this.$message.success('修改成功')
        }
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit () {
      this.$refs.tagForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hDel (id) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await tags.remove({ id })
        this.loadTagList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async  changState (row) {
      if (row.state) {
        row.state = 0
      } else {
        row.state = 1
      }
      try {
        const res = await tags.changeState({ id: row.id, state: row.state })
        console.log(res)
        if (res.status === 200) {
          this.$message.success('操作成功')
        }
      } catch (error) {
        console.log(error)
      }
    },
    async loadTagList () {
      try {
        if (this.$route.query.id) {
          this.q.subjectID = this.$route.query.id
        }
        const res = await tags.list(this.q)
        if (res.status !== 200) return this.$message.error('获取失败')
        this.tagList = res.data.items
        this.total = res.data.counts
        this.alertText = `共${this.total}条数据`
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    async loadSubjectList () {
      try {
        const res = await subjects.list({ page: 1, pagesize: 100 })
        // console.log(res, 'subject')
        if (res.status !== 200) return this.$message.error('获取失败')
        this.subjectList = res.data.items
        console.log(res, 'subject')
      } catch (error) {
        console.log(error)
      }
    },
    hClose () {
      this.$refs.tagForm.resetFields()
      this.tagForm = {
        subjectID: '',
        tagName: ''
      }
    },
    clear () {
      this.searchForm = {
        tagName: '',
        state: ''
      }
      delete this.q.tagName
      delete this.q.state
    },
    async hSearch () {
      this.q = { ...this.q, ...this.searchForm }
      if (this.q.state === '') {
        delete this.q.state
      }
      if (this.q.tagName === '') {
        delete this.q.tagName
      }
      this.loadTagList()
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.q.page = 1
      this.loadTagList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadTagList()
    },
    formatDate (date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    }

  }
}
</script>

<style scoped lang='less'>
.tag-container{
   padding: 0 10px;
    margin: 10px 0;
     .alert {
  margin: 10px 0px;
  }
  .pagination{
    margin: 20px 0;
  }
}
</style>
